package com.wngbms.netty.book._06endec._01;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class IntegerAddDecoder extends ReplayingDecoder<IntegerAddDecoder.PHASE> {

    public enum PHASE {
        PHASE_1,
        PHASE_2,
    }

    int first;
    int second;

    public IntegerAddDecoder() {
        super(PHASE.PHASE_1);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int anInt = in.readInt();
        log.info("decode {}", anInt);
        switch (state()) {
            case PHASE_1:
                first = anInt;
                checkpoint(PHASE.PHASE_2);
                break;
            case PHASE_2:
                second = anInt;
                out.add(first + second);
                checkpoint(PHASE.PHASE_1);
                break;
            default:
                break;
        }
    }
}
